package com.menxin.queueImpl;

/**
 * Created by Menx on 2019/3/11.
 */
public class LinkedHeadTailQueue<E> implements Queue<E> {

    private int size;
    private Node head;
    private Node tail;


    private class Node{
        public E e;
        public Node next;
        public Node(){
            this(null,null);
        }
        public Node(E e,Node next){
            this.e = e;
            this.next = next;
        }
        public Node(E e){
            this(e,null);
        }
    }
    public LinkedHeadTailQueue(){
        size = 0;
        head = null;
        tail = null;
    }

    @Override
    public void add(E e) {
        if(size == 0){
            tail = new Node(e);
            head = tail;
        }else{
            Node curTail = tail;
            tail = new Node(e);
            curTail.next = tail;
        }
        size ++;
    }

    @Override
    public E remove() {
        if(isEmpty()){
            throw new IllegalArgumentException("Queue is Empty");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if(head == null){
            tail = null;
        }

        return retNode.e;
    }

    @Override
    public int getCapcatiy() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E getFront() {
        if(head == null){
            return null;
        }
        return head.e;
    }


    public String toString(){
        Node node = head;
        StringBuilder buf = new StringBuilder();
        buf.append("LinkedHeadTailQueue Head[");
        while(node != null){
            buf.append(node.e).append("->");
        }
        buf.append("Null]End");
        return buf.toString();
    }
}
